package pl.vanta.utils.gui.tables;

import java.awt.Color;
import java.awt.Component;
import java.util.HashMap;
import java.util.Map;

import javax.swing.DropMode;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

public class VJTable extends JTable
{
	private static final long	serialVersionUID	= 1L;

	private Map<Integer, Color>	colorRowMap;

	public VJTable()
	{
		super();

		init();
	}

	public VJTable(int numRows, int numColumns)
	{
		super(numRows, numColumns);

		init();
	}

	public VJTable(Object[][] rowData, Object[] columnNames)
	{
		super(rowData, columnNames);

		init();
	}

	public VJTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm)
	{
		super(dm, cm, sm);

		init();
	}

	public VJTable(TableModel dm, TableColumnModel cm)
	{
		super(dm, cm);

		init();
	}

	public VJTable(TableModel dm)
	{
		super(dm);

		init();
	}

	private void init()
	{
		this.colorRowMap = new HashMap<Integer, Color>();

		this.setFillsViewportHeight(true);
		this.setDropMode(DropMode.INSERT_ROWS);
	}

	@Override
	public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
	{
		Component component = super.prepareRenderer(renderer, row, column);
		component.setBackground(null);
		component = super.prepareRenderer(renderer, row, column);

		if (isCellSelected(row, column))
		{
			component.setBackground(this.getSelectionBackground());
		}
		else
		{
			int realIndex = convertRowIndexToModel(row);
			Color color = this.colorRowMap.get(realIndex);

			if (color != null)
			{
				component.setBackground(color);
			}
		}

		return component;
	}

	public void setColorForRow(Color color, int row, boolean repaint)
	{
		if (row >= 0 && row < this.getModel().getRowCount())
		{
			int realIndex = convertRowIndexToModel(row);

			this.colorRowMap.put(realIndex, color);

			if (repaint)
			{
				repaint();
			}
		}
	}

	public void clearColoredRows()
	{
		this.colorRowMap.clear();

		repaint();
	}

	public void clearRowColor(int row)
	{
		if (row >= 0 && row < this.getModel().getRowCount())
		{
			this.colorRowMap.remove(convertRowIndexToModel(row));

			repaint();
		}
	}
}